package com.itheima.controller;

import com.itheima.feign.UserFeignClient;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jt
 * @date 2021/4/5 21:35
 */
@RestController
@RequestMapping("/consumer")
public class ConsumerController {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private UserFeignClient userFeignClient;

    @GetMapping("/{id}")
    public Map queryById(@PathVariable("id") String id) {
        return userFeignClient.queryById(id);
    }

    @PostMapping
    public String save(@RequestBody Map user) {
        return userFeignClient.save(user);
    }

    @DeleteMapping("/{id}")
    public String delete(@PathVariable("id") String username) {
        return userFeignClient.delete(username);
    }

   /* @GetMapping("/{id}")
    @HystrixCommand(fallbackMethod = "queryByIdFallback")
    public Map queryById (@PathVariable("id") String id) {
//        id = itheima 直接抛异常
        if ("itheima".equals(id)) {
            throw new RuntimeException("太忙了...");
        }

//        restTemplate开启负载均衡注解后, 路径可以直接写服务名称
//        ribbon组件会基于负载均衡算法,帮助我们选择一个服务精心调用
        return restTemplate.getForObject("http://user-service/user/" + id , Map.class);
    }*/

    /**
     * queryById 的服务降级方法
     *
     * @param id
     * @return
     */
    public Map queryByIdFallback(String id) {
        Map map = new HashMap();
        map.put("msg", "服务超时,请稍后重试");
        map.put("code", 500);
        return map;
    }


   /* @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/{id}")
    public Map queryById (@PathVariable("id") String id) {
        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        if (instances != null && !instances.isEmpty()) {
            ServiceInstance serviceInstance = instances.get(0);
            String host = serviceInstance.getHost();
            int port = serviceInstance.getPort();
//            根据id 请求用户微服务中的数据
            return restTemplate.getForObject("http://" + host + ":" + port + "/user/" +id , Map.class);
        }
        //            根据id 请求用户微服务中的数据
        return null;
    }*/

}
